
const mysql = require('mysql');
const connection = mysql.createConnection({
  host     : '101.35.153.65',
  user     : 'tododb',
  password : 'yNeWJwYcn4YGiRRc',
  port:3306,
  database : 'tododb'
});
  connection.connect();
function addItem(data){
   //userlist userid  ???
    var  addSql = 'INSERT INTO todolist(id,title,completed) VALUES(?,?,?)';
    var  addSqlParams = [data.id, data.title,data.completed];
    //增
    connection.query(addSql,addSqlParams)
//更新缓存，

    //     ,function (err, result) {
    // connection.query('SELECT 1 + 1 AS solution', function (error, results, fields) {
    //   if (error) throw error;
    //   console.log('The solution is: ', results[0].solution);
    // });
    
   // connection.end()

}

function updateItem(data){
    //??  update where id=data.id
}
async function editItem(data){
  console.log("___________1______________")
  console.log(data)
  var  addSql = 'update todolist set title = ? ,completed = ? where id=?';
  var  addSqlParams = [ data.title,data.completed,data.id];
  //增
  connection.query(addSql,addSqlParams)
}

async function deleteItem(delid){
    //??  update where id=data.id
    var  delSql = 'delete from todolist where id=?';
    var  delSqlParams = [delid];
    //增
    connection.query(delSql,delSqlParams)
    return 'del ok!!!'
}

async function getTodoList(){

    // 先去缓存里查找，有的话，直接从缓存读取，没有的话，从数据库读取，再存到缓存以便下次请求时使用
    const sql="select * from todolist"
    const mypromise=new Promise((resolve,reject)=>{
        connection.query(sql,function (err, result) {
            if(err){
             reject(err)
              return;
            }
        resolve(result)
    })
    }) 
    const result = await mypromise
    const myarray= JSON.parse(JSON.stringify(result))   //RowDataPacket
    return myarray

    //存到缓存，后面从缓存里面获取
}

/*
async function addItem(data){

    const tlist=await getTodoList()

    tlist.push(data)

    const jstr=JSON.stringify(tlist)
    const key="todolist"
    client.set(key,jstr)
}*/


module.exports = {
    getTodoList,addItem,deleteItem,editItem
}